/**
 * 
 */
package com.ginger.rabbitmq.exchange.api.dlx;

import java.util.HashMap;
import java.util.Map;

import com.ginger.properties.RabbitMQProperties;
import com.ginger.rabbitmq.exchange.api.consumer.GingerConsumer;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @Description:消费者
 * @author 姜锋
 * @date 2019年3月29日 上午9:40:24
 * @version V1.0
 */
public class Consumer {
	public static void main(String[] args) throws Exception {
		// 1.创建连接工厂
		ConnectionFactory connectionFactory = new ConnectionFactory();
		// 1.1设置连接信息
		connectionFactory.setHost(RabbitMQProperties.RABBITMQ_HOST);
		connectionFactory.setPort(RabbitMQProperties.RABBITMQ_PORT);
		connectionFactory.setVirtualHost(RabbitMQProperties.RABBITMQ_VIRTUAL_HOST);
		connectionFactory.setUsername(RabbitMQProperties.USER_NAME);
		connectionFactory.setPassword(RabbitMQProperties.PASSWORD);
		// 2.通过连接工厂创建连接
		Connection connection = connectionFactory.newConnection();
		// 3.通过connection创建
		Channel channel = connection.createChannel();
		// 4.申明正常的交换机队列绑定
				String exchangeName = "test_dlx_exchange";
				String routingKey = "dlx.#";
				String queueName = "test_dlx_queue";
				//4.1声明交换机
				channel.exchangeDeclare(exchangeName, "topic",true,false,null);
				// arguments 属性,要设置到队列上
				Map<String, Object> arguments = new HashMap<>();
				arguments.put("x-dead-letter-exchange","dlx.exchange");
				//4.2明队列
				// channel.queueDeclare(队列名称,是否持久化,是否独占,脱离绑定关系是否自动删除,扩展参数)
				channel.queueDeclare(queueName, true, false, false, arguments);
				//4.3绑定交换机队列指定路由键
				channel.queueBind(queueName, exchangeName, routingKey);
				
				
				//申明死信队列
				String DlxExchangeName = "dlx.exchange";
				String DlxroutingKey = "#";
				String DlxqueueName = "dlx.queue";
				String DlxExchangeType = "topic";
				channel.exchangeDeclare(DlxExchangeName,DlxExchangeType,true,false,null);
				channel.queueDeclare(DlxqueueName, true, false, false, null);
				channel.queueBind(DlxqueueName, DlxExchangeName, DlxroutingKey);
				
				//消费正常队列
				channel.basicConsume(queueName, true, new GingerConsumer(channel));
				//消费死信队列
				channel.basicConsume(DlxqueueName, true, new GingerConsumer(channel));
	}
}
